"use client";
import React from 'react';
import { Drawer, Input, Collapse, Typography, Empty, Spin } from 'antd';
import { CategoryDict, getCategories } from '../lib/api';

const { Panel } = Collapse as any;
const { Text } = Typography;

interface Props {
  open: boolean;
  onClose: () => void;
}

export default function CategoriesDrawer({ open, onClose }: Props) {
  const [search, setSearch] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [items, setItems] = React.useState<CategoryDict[]>([]);

  const fetchData = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await getCategories();
      setItems(data);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    if (open) fetchData();
  }, [open, fetchData]);

  const filtered = React.useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return items;
    return items.filter((x) =>
      x.code.toLowerCase().includes(q) || x.name.toLowerCase().includes(q),
    );
  }, [items, search]);

  return (
    <Drawer
      title="类目清单"
      placement="left"
      width={420}
      open={open}
      onClose={onClose}
      destroyOnClose
    >
      <Input.Search
        placeholder="搜索 code/name"
        allowClear
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        style={{ marginBottom: 12 }}
      />

      {loading ? (
        <div style={{ textAlign: 'center', padding: 24 }}><Spin /></div>
      ) : filtered.length === 0 ? (
        <Empty description="暂无类目" />
      ) : (
        <Collapse accordion>
          {filtered.map((c) => (
            <Panel header={`${c.code} · ${c.name}`} key={c.code}>
              {c.definition && (
                <div style={{ marginBottom: 8 }}>
                  <Text type="secondary">{c.definition}</Text>
                </div>
              )}
              <div>
                <Text>关键词：</Text>
                <div>
                  {(c.keywords || []).length > 0 ? (
                    (c.keywords as string[]).map((k, i) => (
                      <span key={i} style={{ display: 'inline-block', marginRight: 8, marginBottom: 6, padding: '2px 6px', background: '#f5f5f5', borderRadius: 4 }}>{k}</span>
                    ))
                  ) : (
                    <Text type="secondary">暂无关键词</Text>
                  )}
                </div>
              </div>
            </Panel>
          ))}
        </Collapse>
      )}
    </Drawer>
  );
}

